package com.kaluli.project.service;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

import org.apache.log4j.Logger;

import com.kaluli.project.domain.entity.KllOrderSynApi;
/**
 * 等待处理的订单队列对象
 * @author zyzowen1944
 *
 */
public class TradeQueue {
	
	private static Logger log = Logger.getLogger(TradeQueue.class);
	
	private LinkedList<KllOrderSynApi> list = new LinkedList<KllOrderSynApi>();// 队列

	private Set<KllOrderSynApi> set = new HashSet<KllOrderSynApi>();

	private String msgChannel;

	public TradeQueue(String msgChannel) {
		this.msgChannel = msgChannel;
	}

	public synchronized void add(KllOrderSynApi trade) {
		if (!set.contains(trade)) {
			list.addLast(trade);
			set.add(trade);
			log.info("TradeQueue_add_orderNumber:"+trade.getOrderNumber());
			notifyAll();
		}else{
			System.out.println(1);
		}

	}
	
	public synchronized boolean isExist(String orderNumber){
		boolean can = false;
		for(KllOrderSynApi order:set){
			if(order.getOrderNumber().equals(orderNumber)){
				can = true;
				break;
			}
		}
		return can;
	}

	/**
	 * 获取
	 * 
	 * @param trade
	 * @throws InterruptedException
	 */
	public synchronized KllOrderSynApi getQueue() throws InterruptedException {
		while (list.size() <= 0) {
			wait();
		}

		KllOrderSynApi trade = list.removeFirst();
		set.remove(trade);
		notifyAll();
		return trade;
	}
	
	/**
     * 撤销(立即撤销，还在主卖主买队列)
     */
	public synchronized boolean remove(KllOrderSynApi trade) {
		boolean cancelFlag = set.remove(trade);
		cancelFlag =list.removeFirstOccurrence(trade);
		return  cancelFlag;
	}
	
	
	public static void main(String[] args) {
		TradeQueue t = new TradeQueue("ZZ-out");
		KllOrderSynApi trade= new KllOrderSynApi();
		trade.setLogisticJSON("22");
		t.test();
	}
	
	
	public void test(){
		KllOrderSynApi trade= new KllOrderSynApi();
		trade.setLogisticJSON("22");
		if (!set.contains(trade)) {
			list.addLast(trade);
			set.add(trade);
//			log.info("TradeQueue_add_orderNumber:"+trade.getOrderNumber());
//			notifyAll();
			System.out.println("1");
		}
	}
}
